<?php
declare (strict_types = 1);

namespace app;

use think\App;
use think\exception\ValidateException;
use think\Validate;
use think\facade\View;

/**
 * 控制器基础类
 */
abstract class BaseController
{
    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;

    /**
     * 应用实例
     * @var \think\App
     */
    protected $app;

    /**
     * 是否批量验证
     * @var bool
     */
    protected $batchValidate = false;

    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [];

    /**
     * 域名
     * @var string
     */
    protected $host = '';

    /**
     * 控制器
     * @var string
     */
    protected $control = '';

    /**
     * 方法
     * @var string
     */
    protected $action = '';


    /**
     * 企业微信配置
     * @var string
     */
    protected $config = [];


    /**
     * 微信小程序配置
     * @var string
     */
    protected $mini_config = [];



    /**
     * Redis
     * @var string
     */
    protected $redis = [];


    /**
     * 管理员ID
     * @var string
     */
    protected $user_id = [];



    /**
     * 构造方法
     * @access public
     * @param  App  $app  应用对象
     */
    public function __construct(App $app)
    {
        $this->app     = $app;
        $this->request = $this->app->request;

        // 控制器初始化
        $this->initialize();
    }

    // 初始化
    protected function initialize()
    {
        header("Content-type: text/html; charset=utf-8");
        if(!$this->validates($this->request->server('PHP_AUTH_USER'), $this->request->server('PHP_AUTH_PW'))) {
            http_response_code(401);
            header('WWW-Authenticate:Basic realm="My website"'); //对话框显示 http://127.0.0.3 请求用户名和密码。信息为：My website
            echo '需要用户名和密码才能继续访问'; //取消时浏览器输出
            exit;
        }

        $user = session('admin_auth');
        $add = session('add');

        if (empty($user) && empty($add)) {
            return redirect((string)url('Login/spare'))->send();exit;
        }

        $this->user_id = session('admin_auth.id');


        $this->config = [
            'corp_id' => config('app.qywechat.corpid'),

            'agent_id' => config('app.qywechat.agentid'), // 如果有 agend_id 则填写
            'secret'   => config('app.qywechat.corpsecret2'),

            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
        ];

        $this->mini_config = [
            'app_id' => config('app.qywechat.smallappid'),
            'secret'   => config('app.qywechat.smallsecret'),

            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
        ];

        $this->control = $this->request->controller();
        $this->action = $this->request->action();

        $this->host = $this->request->domain();

        View::assign('host',$this->host);
        View::assign('name',session('admin_auth.givenname').' '.session('admin_auth.surname'));
        View::assign('unique_id',$this->control);

        include_once '../extend/Predis/autoload.php';

        $this->redis = new \Predis\Client();
    }


    protected function validates($user, $pass)
    {
        $users = ['loreal'=>'1234567890', 'admin'=>'admin'];
        if(isset($users[$user]) && $users[$user] === $pass) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 验证数据
     * @access protected
     * @param  array        $data     数据
     * @param  string|array $validate 验证器名或者验证规则数组
     * @param  array        $message  提示信息
     * @param  bool         $batch    是否批量验证
     * @return array|string|true
     * @throws ValidateException
     */
    protected function validate(array $data, $validate, array $message = [], bool $batch = false)
    {
        if (is_array($validate)) {
            $v = new Validate();
            $v->rule($validate);
        } else {
            if (strpos($validate, '.')) {
                // 支持场景
                [$validate, $scene] = explode('.', $validate);
            }
            $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
            $v     = new $class();
            if (!empty($scene)) {
                $v->scene($scene);
            }
        }

        $v->message($message);

        // 是否批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }

        return $v->failException(true)->check($data);
    }


    /**
     * 输出错误json
     * @param string $info 信息内容
     * @param number $status 状态 默认失败
     * @param array $data 额外的数据包
     * @param boolean $outputHeader 是否输出头信息
     */
    protected function outputAjax($msg=null, $status=1, $data=array(), $outputHeader=true)
    {
        if (is_array($msg)) {
            $data = $msg;
            $status = 0;
        } else {
            if(is_null($msg)) {
                $msg = '提交信息有误';
            }
            $data = array(
                'msg'=> $msg,
                'status'=> $status,
                'data'=> $data
            );
        }

        if($outputHeader) {
            header('Content-Type:application/json; charset=utf-8');
        }
        return json($data);
    }

}
